import { Injectable } from "@nestjs/common";
import { CreateRoleApiDto } from "./dto/create-role-api.dto";
import { UpdateRoleApiDto } from "./dto/update-role-api.dto";
import { ResultData } from "@/common/utils/result";
import { RoleApi } from "@/modules/system/role-api/entities/role-api.entity";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";

@Injectable()
export class RoleApiService {
    constructor(
        @InjectRepository(RoleApi)
        private readonly roleApiRepository: Repository<RoleApi>
    ) {
    }
    
    create(createRoleApiDto: CreateRoleApiDto) {
        return "This action adds a new roleApi";
    }
    
    findAll() {
        return `This action returns all roleApi`;
    }
    
    findOne(id: number) {
        return `This action returns a #${id} roleApi`;
    }
    
    update(id: number, updateRoleApiDto: UpdateRoleApiDto) {
        return `This action updates a #${id} roleApi`;
    }
    
    remove(id: number) {
        return `This action removes a #${id} roleApi`;
    }
    
    async roleAddApi({ roleId, apiIds }) {
        // 删除大于100000的id
        const newApiIds = apiIds.filter(v => (v < 100000));
        // 删除所有再新增
        await this.roleApiRepository.delete({ roleId });
        return ResultData.ok(
            await this.roleApiRepository.save(
                newApiIds.map(v => ({ roleId: roleId, apiId: v }))
            )
        );
    }
    
    async getApiIdByRoleId({ roleId }) {
        const res = await this.roleApiRepository.find({ where: { roleId }, relations: ["api"] });
        return ResultData.ok(res.map(v => (v.apiId)));
    }
}
